package cn.tedu.property_management_system.security;

import cn.tedu.property_management_system.entity.VO.UserVO;
import cn.tedu.property_management_system.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class MangerUserDetailsService implements UserDetailsService {

    @Autowired
    UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        log.debug("根据用户名[{}]查询用户",s);
        UserVO userVO = userMapper.findByUsername(s);
        log.debug("查找到的用户信息为[{}]",userVO);
        if (userVO==null){
            throw new BadCredentialsException("登录失败,用户名不存在");
        }
        log.debug("验证用户名密码,封装权限[{}]及角色信息[{}]其他信息返回安全上下文对象"
                ,userVO.getPermissions(),userVO.getRoleIds());
        UserDetails build = User.builder()
                .username(userVO.getUsername())
                .password(userVO.getPassword())
                .authorities(userVO.getPermissions().toArray(new String[]{}))
                //.roles(userVO.getRoleIds().toArray(new String[]{}))
                //roles和authorities都是向User的authorities属性赋值,二者是冲突的
                .accountExpired(false)
                .credentialsExpired(false)
                .disabled(false)
                .accountLocked(false).build();
        log.debug("将向Spring Security返回尝试登录的用户信息：{}", build);
        return build;
    }
}
